package com.datareport.data.Handler;


import com.alibaba.fastjson.JSON;
import com.datareport.data.dto.ResultDTO;
import com.datareport.data.exception.CustomizeErrorCode;
import com.datareport.data.exception.CustomizeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice
@Slf4j
public class CustomizeExceptionHandler {
    @ExceptionHandler(Exception.class)
    ModelAndView handle(Throwable e, Model model, HttpServletRequest request, HttpServletResponse response) throws Throwable {

        String contentType = request.getContentType();

        if ("application/json".equals(contentType)) {
            //返回JSON
            ResultDTO resultDTO;

            if(e instanceof CustomizeException){
                resultDTO= ResultDTO.errorOf((CustomizeException)e);
            }else {
                resultDTO= ResultDTO.errorOf(CustomizeErrorCode.SYS_ERROR);
            }
            try {
                response.setContentType("application/json");
                response.setStatus(200);
                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(resultDTO));
                writer.close();
            }catch (IOException ioException){

            }
            return null;
        } else {
            // 错误页面跳转
            if (e instanceof CustomizeException) {
                model.addAttribute("message", e.getMessage());
            } else {
                //全局异常捕捉优先级高于JwtAccessDeniedHandler，所以只能在这里重新抛出
                // 如果是权限不足异常，则重新抛出去，让JwtAccessDeniedHandler捕获进行处理
                if (e instanceof AccessDeniedException || e instanceof AuthenticationException) {
                    throw e;
                }
                log.error("handle error", e);
                model.addAttribute("message", CustomizeErrorCode.SYS_ERROR.getMessage());
            }
            return new ModelAndView("error");
        }
    }
}


